1679D - Toss a Coin to Your Graph - CodeForces Solution


binary search dfs and similar dp graphs *1900

Please click on ads to support us..

C++ Code:

#include<iostream>
#include<vector>
#include<algorithm>
#include<cmath>
#include<queue>
#include<stack>
#include<set>
#include<string>
#define pll pair<long long,long long>
#define F first
#define S second
typedef long long ll;
using namespace std;
vector<vector<ll> > gr;
vector<ll>colors;
vector<ll>topik;
bool cycl = 0;
vector<ll>a;
void dfs(ll v,ll wei)
{
	colors[v] = 1;
	for (auto f : gr[v])
	{
		if (a[f]<=wei&&colors[f] == 0)dfs(f,wei);
		else if (a[f]<=wei&&colors[f] == 1)cycl = 1;
	}
	colors[v] = 2;
}
void top_sort(ll v,ll wei)
{
	colors[v] = 1;
	for (auto f : gr[v])if (a[f]<=wei&&colors[f] == 0)top_sort(f,wei);
	topik.push_back(v);
}
vector<ll>d;
ll mx = -1e9;
void dfs3(ll v,ll wei)
{
	d[v] = 1;
	colors[v] = 1;
	for (auto y : gr[v])
	{
		if (a[y] <= wei)
		{
			if (colors[y] == 0)dfs3(y, wei);
			d[v] = max(d[v], d[y] + 1);
		}
	}
	mx = max(mx, d[v]);
}
int main()
{
	cin.tie(0)->sync_with_stdio(0);
	cout.tie(0);
	ll n, m, k;
	cin >> n >> m >> k;
	a.resize(n);
	colors.resize(n, 0);
	gr.resize(n);
	for (ll i = 0; i < n; ++i)cin >> a[i];
	ll vf, vs;
	for (ll i = 0; i < m; ++i)
	{
		cin >> vf >> vs;
		--vf, --vs;
		gr[vf].push_back(vs);
	}
	ll r = 1e9+7, l = 0, mi;
	while (r - l > 1)
	{
		mi = (r + l) >> 1;
		cycl = 0;
		colors.assign(n, 0);
		for (ll i = 0; i < n; ++i)if (a[i] <= mi&&colors[i]==0)dfs(i, mi);
		if (cycl)
		{
			r = mi;
			continue;
		}
		colors.assign(n, 0);
		topik.clear();
		for (ll i = 0; i < n; ++i)if (a[i]<=mi&&colors[i] == 0)top_sort(i,mi);
		reverse(topik.begin(), topik.end());
		mx = -1e9;
		d.assign(n, 0);
		colors.assign(n, 0);
		for (ll i = 0; i <topik.size(); ++i)
		{
			if (colors[topik[i]] == 0)dfs3(topik[i], mi);
		}
		if (mx >= k)r = mi;
		else l = mi;
	}
	if (r > 1e9)cout << -1 << '\n';
	else cout << r << '\n';
	return 0;
}


Comments

Submit
0 Comments
More Questions

1515E - Phoenix and Computers
1552B - Running for Gold
994A - Fingerprints
1221C - Perfect Team
1709C - Recover an RBS
378A - Playing with Dice
248B - Chilly Willy
1709B - Also Try Minecraft
1418A - Buying Torches
131C - The World is a Theatre
1696A - NIT orz
1178D - Prime Graph
1711D - Rain
534A - Exam
1472A - Cards for Friends
315A - Sereja and Bottles
1697C - awoo's Favorite Problem
165A - Supercentral Point
1493A - Anti-knapsack
1493B - Planet Lapituletti
747B - Mammoth's Genome Decoding
1591C - Minimize Distance
1182B - Plus from Picture
1674B - Dictionary
1426C - Increase and Copy
520C - DNA Alignment
767A - Snacktower
1365A - Matrix Game
714B - Filya and Homework
31A - Worms Evolution